// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { id } = event
    
    if (!id) {
      return {
        success: false,
        message: '商品ID不能为空'
      }
    }
    
    // 查询商品信息
    const productResult = await db.collection('products').doc(id).get()
    const product = productResult.data
    
    if (!product) {
      return {
        success: false,
        message: '商品不存在'
      }
    }
    
    // 查询商品的评价预览
    const reviewResult = await db.collection('reviews')
      .where({
        productId: id,
        status: 'approved' // 只查询已审核的评价
      })
      .orderBy('createdAt', 'desc')
      .limit(1)
      .get()
    
    // 如果有评价，添加评价预览信息
    if (reviewResult.data && reviewResult.data.length > 0) {
      const review = reviewResult.data[0]
      // 查询用户信息
      const userResult = await db.collection('users').doc(review.userId).get()
      const user = userResult.data
      
      product.reviewPreview = {
        id: review._id,
        userId: review.userId,
        userName: user ? (user.nickName || '匿名用户') : '匿名用户',
        userAvatar: user ? (user.avatarUrl || '') : '',
        content: review.content,
        images: review.images || [],
        rating: review.rating,
        createdAt: review.createdAt
      }
    }
    
    // 查询商品评价总数
    const reviewCountResult = await db.collection('reviews')
      .where({
        productId: id,
        status: 'approved'
      })
      .count()
    
    product.reviewCount = reviewCountResult.total || 0
    
    // 增加商品浏览量
    await db.collection('products').doc(id).update({
      data: {
        viewCount: _.inc(1)
      }
    })
    
    // 返回商品信息
    return {
      success: true,
      data: product
    }
  } catch (error) {
    console.error(error)
    return {
      success: false,
      message: error.message
    }
  }
} 